/* @(#)client.c
 * Time-stamp: <2008-10-13 21:23:11 root>
 * Copyright 2008 Julian Qian
 * Author: root@localhost.localdomain
 * Version: $Id: client.c,v 0.0 2008/10/04 02:58:58 root Exp $
 * Keywords: 
 */

#include "common.h"

void
dg_cli(FILE *fp, int sockfd, const SA *pservaddr){
	int				n;
	char			buffer[PROTO_LENG], recvbuf[PROTO_LENG+1], cmd[MAXLEN];
	socklen_t		len, servlen;
	char type, data;

	devid_t devid = 2;

	/* $$$$$$$$$$$$$$$$ */
	/* combine buffer package */
	/* 1: length */
	buffer[0] = 0x0C;
	/* 2~3: Device board address */
	buffer[1] = 0x00;
	buffer[2] = 0x28;
	/* 4~6: Device Unique ID */
	cvt_di(devid, buffer + PROTO_DEVI);
	/* 7~8: device version */
	buffer[6] = 0x01;
	buffer[7] = 0x00;
	/* 9~10: function description */
	buffer[8] = 0xf0;
	buffer[9] = 0x00;
	/* 11~12: Reserved */
	buffer[10] = 0x00;
	buffer[11] = 0x00;
	/* 13~14: sequance number */
	buffer[12] = 0x00;
	buffer[13] = 0x00;
	/* 15: data length */
	buffer[14] = 0x02;
	/* 16: data type */
	buffer[15] = 0x00;  /* send from server */
	/* 17: data detail */
	buffer[16] = 0x00;

	while (fgets(cmd, MAXLINE, fp) != NULL) {
		type = cmd[0];
		data = cmd[1];
		
		switch(type){
		default:
			buffer[15] = type - '0';
			buffer[16] = data - '0';
		}
		sendto(sockfd, buffer, PROTO_LENG, 0, pservaddr, sizeof(SA));
		printf("Send:\t");
		print_hex(buffer, PROTO_LENG);
		printf("\n");
		
		n = recvfrom(sockfd, recvbuf, PROTO_LENG+1, 0, NULL, NULL);
		recvbuf[n] = 0;	/* null terminate */
		printf("Received:\t");
		print_hex(recvbuf, PROTO_LENG);
		printf("\n");
	}
}


int main(int argc, char *argv[])
{
    int fd;
	int len, n;
	char ip[IP_ANON_SIZE];

	struct sockaddr_in server_addr;

	if(argc!=2){
		printf("USAGE: %s <IP address>\n", argv[0]);
		memcpy(ip, "218.61.194.12", IP_ANON_SIZE);		
	}else{
		memcpy(ip, argv[1], IP_ANON_SIZE);
	}

	bzero(&server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(SERVER_PORT);
	server_addr.sin_addr.s_addr = inet_addr(ip);
	/* server_addr.sin_addr.s_addr = inet_addr("218.61.194.12"); */

	printf("send mesage to IP: %s\n", ip);

	len = sizeof(server_addr);
	fd = socket(AF_INET, SOCK_DGRAM, 0);

	dg_cli(stdin, fd, (SA *)&server_addr);
	
    return 0;
}


